package com.itheima.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.codehaus.jettison.json.JSONObject;

import java.util.Random;

public class SMSUtil {

    private static final String regionId = "cn-hangzhou";

    private static final String accessKeyId = "LTAI4G6LpWr5fPirs1TapLeH";

    private static final String accessSecret = "AGxqR28MCZywLttjAp3oqfd9v8CHBM";

    private static final String signName = "传智健康";

    private static final String SMS_VALIFYCODE_TEMPLATECODE = "SMS_201652315";//短信验证码模板code

    private static final Integer CODE_BIT = 6;//验证码的位数

    public static String sendSmsCode(String telphone){
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", regionId);
        //手机号
        request.putQueryParameter("PhoneNumbers", telphone);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", SMS_VALIFYCODE_TEMPLATECODE);
        String code = generatorCode(CODE_BIT);
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            JSONObject jsonObject = new JSONObject(response.getData());
            String res = (String) jsonObject.get("Code");
            System.out.println(res);
            if("OK".equals(res)){
                return code;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 4位或者6位
     * @param num 生成的验证码的位数
     * */
    public static String generatorCode(Integer num){
        if(num == null || (num !=4 && num != 6)){
            throw new RuntimeException("必须是4位或者是6位");
        }
        // 4 1000~9999
        Random random = new Random();
        if(num == 4){
            return String.valueOf(random.nextInt(9000) + 1000);
        }else{
            return String.valueOf(random.nextInt(900000) + 100000);
        }
    }

}
